from google.appengine.ext import db
from keystring import KeyString

def split_str_list(string):
  """ Converts str to list """
  string = string or ''
  for char in ';':
    string = string.replace(char,',')  
  return [KeyString(s.strip()) for s in string.split(',')]

class KeyStringListProperty(db.ListProperty):
  verbose_type = 'Keyword List'
  
  def __init__(self, *args, **kwargs):
    super(KeyStringListProperty, self).__init__(basestring, *args, **kwargs)
  
  def make_value_from_datastore(self, value):
    if not value: return None
    # Grab first half -- (the actual unicode values)
    return [KeyString(value) for value in value[:len(value) / 2]]
  
  def make_value_for_query(self, value):
    if value is None: return value
    return KeyString(value).key
    
  def get_value_for_datastore(self, model_instance):
    value = super(KeyStringListProperty, self)\
      .get_value_for_datastore(model_instance) or []
    key_list = []
    unicode_list = []
    for item in value:
      key_list.append(KeyString(item).key)
      unicode_list.append(unicode(item))
    return unicode_list + key_list
  
  def get_value_for_lookup(self, model_instance):
    value = self.get_value_for_datastore(model_instance)
    if value:
      return value[(len(value) / 2):]
  
  def get_value_for_sort(self, model_instance):
    return self.get_value_for_lookup(model_instance)
  
  def get_value_for_tag(self, model_instance):
    value = super(KeyStringListProperty, self)\
      .get_value_for_datastore(model_instance) or []
    return [unicode(item) for item in value]
  
  def validate(self, value):
    if hasattr(value, '__iter__'):
      value = [KeyString(s) for s in value]
    elif isinstance(value, basestring):
      value = split_str_list(value)
    return super(KeyStringListProperty, self).validate(value)
